#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 31/3/2024 下午9:30
# Author: name
# File: case_to_py.py
# ide: PyCharm
# description: yaml测试用例转化为.py文件
import os
import time

from pywebio.output import put_button
from pywebio.pin import pin, put_file_upload
from ruamel import yaml

from back_end.auto_test.tools.fiel_tools import read_file, write_to_file

TEST_SUITE_TEMP_PATH = "../templates/test_suite.pytemp"
TEST_STEP_TEMP_PATH = "../templates/test_step.pytemp"
TEST_SETUP_TEMP_PATH = "../templates/setup.pytemp"
TEST_TEARDOWN_TEMP_PATH = "../templates/teardown.pytemp"


class CaseToPy:

    def __init__(self, yml_case_file_list: list):
        self.yml_case_list = yml_case_file_list

        pass

    def create_test_case(self):
        # print(yml_case_file_list)
        print(os.path.abspath(""))
        test_case_dir = f"../py_scripts/{int(time.time() * 1000)}"
        os.mkdir(test_case_dir)
        for yml_case_data in self.yml_case_list:
            print(yml_case_data)
            yml_case = yaml.load(yml_case_data["content"], Loader=yaml.UnsafeLoader)
            py_file_name = yml_case_data["filename"].split(".")[0]
            print(yml_case)
            test_suite_temp = read_file(TEST_SUITE_TEMP_PATH)
            print(test_suite_temp)
            test_suite_temp = test_suite_temp.replace("{{suite_name}}", py_file_name).replace("{{suite_desc}}",
                                                                                              yml_case[
                                                                                                  "suite_desc"])
            write_to_file(f"{test_case_dir}/test_{py_file_name}.py", test_suite_temp, "a")
            for case in yml_case["test_steps"]:
                """
                    参数处理需要在发送请求之前处理,否则,动态提取的参数无法在第一时间进行获取到
                """
                # case = handle_params(json.dumps(case, ensure_ascii=False))
                case["request"]["path"] = case["request"]["path"]
                print("转化后的参数", case)
                setup_temp = read_file(TEST_STEP_TEMP_PATH)
                teardown_temp = read_file(TEST_TEARDOWN_TEMP_PATH)
                test_step_temp = read_file(TEST_SETUP_TEMP_PATH)
                if case["request"].get("setup"):
                    write_to_file(f"{test_case_dir}/test_{py_file_name}.py", setup_temp, "a")
                if case["request"].get("teardown"):
                    write_to_file(f"{test_case_dir}/test_{py_file_name}.py", teardown_temp, "a")
                test_step_temp = test_step_temp.replace("{{step_desc}}", case["step_desc"]).replace("{{case_info}}",
                                                                                                    str([
                                                                                                        case])).replace(
                    "{{step_name}}",

                    case["step_name"].replace("${", "").replace("}$", "") if "${" in case["step_name"] else case[
                        "step_name"])
                write_to_file(f"{test_case_dir}/test_{py_file_name}.py", test_step_temp, "a")


if __name__ == '__main__':
    def business_exec_case():
        yml_test_case_list = pin.yml_case_files
        print(yml_test_case_list[0]["filename"])
        ctp = CaseToPy(yml_test_case_list)
        ctp.create_test_case()


    put_file_upload("yml_case_files", placeholder="请选择测试用例", accept=[".yml", ".yaml"],
                    multiple=True)
    put_button("执行", onclick=lambda: business_exec_case())
